#define _SVID_SOURCE  1
#include <header.h>

/* 此版本为传输大文件 */
int main(int argc, char* argv[]){
	ARGS_CHECK(argc, 1);

	char *ip = "192.168.169.128";
	char *port = "8080";

	int net_fd = socket(AF_INET, SOCK_STREAM, 0);

	struct sockaddr_in client_addr;
	client_addr.sin_family = AF_INET;
	client_addr.sin_port = htons(atoi(port));
	client_addr.sin_addr.s_addr = inet_addr(ip);

	connect(net_fd, (struct sockaddr*)&client_addr, sizeof(client_addr));
	
    
    
    off_t file_size;
	recv(net_fd, &file_size, sizeof(off_t), MSG_WAITALL);


	// 先传文件名的长度，再传文件名
	int name_len = 0;
	recv(net_fd, &name_len, sizeof(int), MSG_WAITALL);
	
    char fileName[60] = {0};
    recv(net_fd, fileName, name_len, MSG_WAITALL);
    printf("fileName: %s \n", fileName);

    int file_fd = open(fileName, O_WRONLY | O_CREAT, 0600);

    off_t now_size = 0;
    while(1){
        ssize_t file_len =0;
        ssize_t res = recv(net_fd, &file_len, sizeof(ssize_t), MSG_WAITALL);
        if(res == 0){
            // 对方关闭链接, 数据发完了
            break;
        }
        
		char buf[1024] = {0};
        res = recv(net_fd, buf, file_len, MSG_WAITALL);
        if(res == 0){
            // 对方关闭链接, 数据发完了
            break;
        }
        
        // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        // 逆天大bug,写入因该是发过来的file_len,而不是strlen(buf)
        // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        ssize_t byte = write(file_fd, buf, file_len);
        ERROR_CHECK(byte, -1, "write");

        now_size += res;
        printf("进度条%.2f\n", (double) now_size *100 /file_size);
    }

	close(file_fd);
	close(net_fd);
	return 0;
}